/**
 * 
 */
package org.sensmon.gui;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import javax.swing.SwingUtilities;

/**
 * @author LAP
 *
 */
public class SensorGUIInvocationHandler implements InvocationHandler {

	private Object invocationResult = null;
	
	private SensorGUICallback callback;
	
	public SensorGUIInvocationHandler(SensorGUICallback callback) {
		this.callback = callback;
	}
	
	@Override
	public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
		RequiresInEDT annotation = method.getAnnotation(RequiresInEDT.class);
		if (annotation != null) {
			if (SwingUtilities.isEventDispatchThread()) {
				invocationResult = method.invoke(callback, args);
			} else {
				Runnable runnable = new Runnable() {	
					@Override
					public void run() {
						try {
							invocationResult = method.invoke(callback, args);
						} catch (Exception e) {
							throw new RuntimeException(e);
						}
					}
				};
				if (RequiresInEDTPolycy.ASYNCHRONOUS.equals(annotation.value())) {
					SwingUtilities.invokeLater(runnable);
				} else {
					SwingUtilities.invokeAndWait(runnable);
				}
			}
		} else {
			invocationResult = method.invoke(callback, args);
		}
		return invocationResult;
	}

}
